<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Request;

class Post extends Home
{
    public function __construct()
    {
        //继承底层的控制器构造函数
        parent::__construct();

        //定义一个全局模型
        // $this->UserModel = model('User.User');
        // $this->PostModel = model('Post.Post');
        // $this->CollectModel = model('User.Collect');
        // $this->RecordModel = model('User.Record');
        $this->ConfigModel = model('Config');
        $this->CateModel = model('Post.Cate');
        $this->PostModel = model('Post.Post');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
        $this->CollectModel = model('User.Collect');

    }
    //用户中心 我的帖子
    public function index()
    {
        $bg = $this->request->param('bg', '');
        //查询帖子
        $postses = $this->PostModel->where(['userid' =>$this->LoginUser['id']])->order('createtime','desc')->paginate(10);
        
        $postssun = $this->PostModel->where(['userid' =>$this->LoginUser['id']])->order('createtime','desc')->select();
        
        //分页调用
        $pagestr = $postses->render();

        //赋值
        $this->assign([
            'posts' => $postses,
            'pagestr' => $pagestr,
            'postssun' => count($postssun),
            //侧栏选中样式渲染
            'bg' => $bg,
        ]);

        //渲染模板
        return $this->fetch();
    }

    //新建发帖
    public function add()
    {
        if($this->request->isPost())
        {
            // 接收全部参数
            $param = $this->request->param();
            // halt($param);

            // 验证码是否正确
            if(!captcha_check($param['vercode'])){
                $this->error('验证码错误，请重新输入');
                exit;
            }

            // 获取到附加功能的积分
            $StatePoint = model('Config')->where(["key" => "StatePoint{$param['state']}"])->value('value');

            // 获取悬赏积分
            $AcceptPoint = $param['point'];

            // 附加功能的积分 + 悬赏积分  bcadd 两个任意精度数字的加法计算
            $Point = bcadd($StatePoint,$AcceptPoint);

            // 用户 => 当前登录的用户
            $UserPoint = $this->LoginUser['point'];

            // 用户的积分 - (附加功能的积分 + 悬赏积分)
            $point = bcsub($UserPoint,$Point);

            // 判断用户是否够发帖
            if($point < 0)
            {
                $this->error('你的当前积分不足，请重新充值');
                exit;
            }

            // 帖子插入帖子表 => 更新用户的积分(对用户表进行操作) => 用户的所有消费行为都会记录消费记录表

            // 开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 帖子的数据
            $PostData = [
                'title' => $param['title'],
                'content' => $param['content'],
                'point' => $AcceptPoint,
                'state' => $param['state'],
                'cateid' => $param['cateid'],
                'userid' => $this->LoginUser['id']
            ];

            $PostResult = $this->PostModel->validate('common/Post/Post')->save($PostData);

            if($PostResult === FALSE)
            {
                $this->error($this->PostModel->getError());
                exit;
            }


            // 消费记录
            $RecordData = [
                'point' => $Point,
                'state' => 1,
                'userid' => $this->LoginUser['id']
            ];

            //判断消费状态
            switch($param['state'])
            {
                case 1:
                    $RecordData['content'] = "【".$PostData['title']."】采纳积分:<b>".$AcceptPoint."积分</b> 置顶：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                case 2:
                    $RecordData['content'] = "【".$PostData['title']."】采纳积分:<b>".$AcceptPoint."</b>积分 精华：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                case 3:
                    $RecordData['content'] = "【".$PostData['title']."】采纳积分:<b>".$AcceptPoint."</b>积分 热门：<b>{$StatePoint}积分</b> - 发布时间：".date("Y-m-d H:i");
                    break;
                default:
                    $RecordData['content'] = "【".$PostData['title']."】采纳积分:<b>".$AcceptPoint."</b>积分 - 发布时间：".date("Y-m-d H:i");
                    break;
            }

            $RecordResult = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if($RecordResult === FALSE)
            {
                // 回滚事务
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 更新用户的积分
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $point
            ];

            $UserResult = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserResult === FALSE)
            {
                // 回滚事务
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 大判断
            if($PostResult === FALSE || $RecordResult === FALSE || $UserResult === FALSE)
            {
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->error('发布悬赏帖子失败，请重新操作');
                exit;
            }else{
                // 提交事务
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->UserModel->commit();
                $this->success('发布悬赏帖子成功',url('home/index/index'));
                exit;
            }

        }

        // 获取附加功能
        $stateList = $this->PostModel->state();

        // 查询分类
        $cateList = $this->CateModel->order('weigh','asc')->select();
        $this->assign([
            'cateList' => $cateList,
            'stateList' => $stateList
        ]);
        return $this->fetch();
    }
    // 删除帖子
    public function del()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0);

            $result = $this->PostModel->destroy($id);

            $data = [
                'code' => 0,
                'msg' => '未知信息'
            ];

            if ($result === FALSE) {
                $data['msg'] = '删除失败,请重新操作';
                echo json_encode($data);
                exit;
            } else {
                $data = [
                    'code' => 1,
                    'msg' => '删除成功'
                ];
                echo json_encode($data);
                exit;
            }
        }
    }
    //编辑帖子
    public function edit()
    {

        //查询所有的分类
        $catelist = model('Post.Cate')->order('weigh', 'asc')->select();

        $postid = $this->request->param('postid', 0);

        //根据id去查询这个帖子是否存在
        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('编辑的帖子不存在');
            exit;
        }

        //判断登录用户id  和 发帖人的userid 是否相同
        if ($post['userid'] != $this->LoginUser['id']) {

            $this->error('无权修改此帖');
            exit;
        }

        //判断是否有post过来
        if ($this->request->isPost()) {

            //获取全部数据
            $params = $this->request->param();


            //获取参数 如果没有就默认为空
            $vercode = $this->request->param('vercode', '');

            //判断验证码是否正确 如果结果返回true就是正确否则失败
            if (!captcha_check($vercode)) {
                $this->error('验证码输入错误');
                exit;
            }

            //组装数据
            $data = [
                'id' => $postid,
                'title' => $params['title'],
                'cateid' => $params['cateid'],
                'content' => $params['content']
            ];

            $result = $this->PostModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                //修改失败
                $this->error($this->PostModel->getError());
                exit;
            } else {
                //修改成功
                $this->success('修改成功', url('home/index/info', ['postid' => $postid]));
                exit;
            }
        }


        $this->assign([
            'catelist' => $catelist,
            'post' => $post
        ]);
        //渲染模板
        return $this->fetch();
    }
    //用户中心 我的收藏
    public function collect()
    {   
        $bg = $this->request->param('bg', '');

        $posrCollt = $this->CollectModel->with(['post'])->where(['collect.userid' =>$this->LoginUser['id']],)->order('createtime','desc')->paginate(10);
        
        $postssun = $this->CollectModel->with(['post'])->where(['collect.userid' =>$this->LoginUser['id']],)->order('createtime','desc')->select();

        //分页调用
        $pagestr = $posrCollt->render();

        // var_dump($posrCollt);
        // exit;
        //  $count = $this->CommentModel->where(['postid' => $postid])->count();

        $this->assign([
            'posrCollt' => $posrCollt,
            'pagestr' => $pagestr,
            'postssun' => count($postssun),
            //侧栏选中样式渲染
            'bg' => $bg,
        ]);

        return $this->fetch();
    }

}
